package com.platform.study.thread.threadpool;

import java.util.LinkedList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: wangyanginfo
 * Date: 13-1-5
 * Time: 下午3:57
 * To change this template use File | Settings | File Templates.
 */
public class BlockingQueue {

    private List queue = new LinkedList();

    private int limit = 10;

    public BlockingQueue(int limit) {
        this.limit = limit;
    }

    public synchronized Object enqueue(Object item) throws InterruptedException {
        while (this.queue.size() == this.limit) {
            System.out.println("Arrive to the pool's max size:" + this.limit);
            wait();
        }
        if (this.queue.size() == 0) {
            notifyAll();
        }

        System.out.println("Add a new thread to the pool.Pool's size before adding:" + this.queue.size());
        this.queue.add(item);

        return this.queue.get(this.queue.size() - 1);
    }

    public synchronized Object dequeue() throws InterruptedException {
        while (this.queue.size() == 0) {
            System.out.println("Pool's size is 0.");
            wait();
        }
        if (this.queue.size() == this.limit) {
            notifyAll();
        }

        System.out.println("Remove a thread from the pool.Pool's size before removing:" + (this.queue.size() - 1));
        return this.queue.remove(0);
    }

    public synchronized int size() {
        return this.queue.size();
    }

}
